package com.heimo.babyage;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.heimo.babyage.core.DateHelper;
import com.heimo.babyage.core.LogHelper;

public class BabyAgeWidgetService extends Service {
	private final IBinder mBinder = new LocalBinder();
	private static final String TAG = "BabyAgeWidgetService";
	
	private AlarmManager alarmManager = null;
	private PendingIntent pi = null;
	
	@Override
    public void onCreate() {
		LogHelper.log(TAG, "[onCreate]");
		super.onCreate();
		pi = this.getPi();
    }
/*	
	@Override
	public void onStart(Intent intent, int startId) {
		LogHelper.log(TAG, "[onStart]");
		handleCommand(intent);
	}
*/
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		LogHelper.log(TAG, "[onStartCommand]");
		handleCommand(intent);
	    return super.onStartCommand(intent, flags, startId);
	}

	private void handleCommand(Intent intent) {		
		long milliisTarget = DateHelper.getAlarmWakeUpTime();
		alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		alarmManager.set(AlarmManager.RTC_WAKEUP, milliisTarget, pi);
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		LogHelper.log(TAG, "[onDestroy]");
		if(this.pi!=null){
			alarmManager.cancel(pi);
		}
	}
	
	@Override
    public IBinder onBind(Intent intent) {
		LogHelper.log(TAG, "[onBind]");
        return mBinder;
    }
		
	public class LocalBinder extends Binder {
		BabyAgeWidgetService getService() {
            return BabyAgeWidgetService.this;
        }
    }
	
	/*
	 * Private function
	 * */
	
	private PendingIntent getPi(){
		Intent i = new Intent(this, BabyAgeWidgetProvider.class);
		String eventName = this.getApplicationContext().getResources().getString(R.string.widget_event_name);
		i.setAction(eventName);
		return PendingIntent.getBroadcast(this, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
	}
}
